package com.third.customer.model.dao.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.third.customer.model.dao.UserDao;
import com.third.customer.model.dao.param.UserParam;
import com.third.customer.model.mapper.UserMapper;
import com.third.customer.model.tables.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.Optional;

/**
 * Created by hehuaichun on 2020/5/19.
 */
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean insert(User user) {
        return userMapper.insert(user) == 1;
    }

    @Override
    public boolean update(User user) {
        return userMapper.updateById(user) == 1;
    }

    @Override
    public boolean deleteById(Long id) {
        return userMapper.deleteById(id) == 1;
    }

    @Override
    public Optional<User> getById(Long id) {
        return Optional.ofNullable(userMapper.selectById(id));
    }

    @Override
    public Optional<User> getByName(Long companyId, String name) {
        return new LambdaQueryChainWrapper<>(userMapper)
                .eq(User::getCompanyId, companyId)
                .eq(User::getName, name).list().stream().findFirst();
    }

    @Override
    public Page<User> query(UserParam param) {
        Page<User> page = new Page<>(param.getPage(), param.getLimit());
        page.addOrder(OrderItem.desc("id"));
        return new LambdaQueryChainWrapper<>(userMapper)
                .eq(!StringUtils.isEmpty(param.getCompanyId()), User::getCompanyId, param.getCompanyId())
                .like(!StringUtils.isEmpty(param.getName()), User::getName, param.getName())
                .eq(param.getType() != null, User::getType, param.getType())
                .page(page);
    }
}
